# 构建参数
ARG NODE_VERSION=23
ARG GO_VERSION=1.24

# 前端构建阶段
FROM node:${NODE_VERSION}-alpine AS frontend-builder

# 设置工作目录
WORKDIR /app

# 1. 安装pnpm
RUN npm install -g pnpm@latest

# 2. 复制依赖文件
COPY WEB/package.json WEB/pnpm-lock.yaml ./

# 3. 安装生产依赖
RUN pnpm install --prod --frozen-lockfile

# 4. 复制前端源代码
COPY WEB/ ./

# 5. 构建前端应用
RUN pnpm build

# Go多架构构建阶段
FROM golang:${GO_VERSION}-alpine AS backend-builder

# 设置工作目录
WORKDIR /app

# 安装必要的工具
RUN apk add --no-cache git build-base

# 设置Go环境
ENV GOPROXY=https://goproxy.cn,direct \
    GOSUMDB=sum.golang.org \
    CGO_ENABLED=1

# 复制go模块文件
COPY go.mod go.sum ./

# 下载依赖
RUN go mod download

# 复制项目文件
COPY . .

# 从前端构建阶段复制dist目录
COPY --from=frontend-builder /app/dist ./internal/v2/web/dist

# 编译多架构应用
RUN --mount=type=cache,target=/root/.cache/go-build \
    GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o ssh-detector-amd64 ./cmd/main.go && \
    GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o ssh-detector-arm64 ./cmd/main.go

# 最终运行阶段
FROM alpine:latest

# 设置工作目录
WORKDIR /app

# 安装必要的运行时依赖
RUN apk --no-cache add ca-certificates tzdata && \
    cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone

# 复制所有架构的可执行文件和启动脚本
COPY --from=backend-builder /app/ssh-detector-amd64 /app/
COPY --from=backend-builder /app/ssh-detector-arm64 /app/
COPY start.sh /app/

# 设置执行权限
RUN chmod +x /app/start.sh /app/ssh-detector-amd64 /app/ssh-detector-arm64

# 暴露端口
EXPOSE 8080

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s \
    CMD wget --no-verbose --tries=1 --spider http://localhost:8080/healthz || exit 1

# 使用启动脚本作为入口点
CMD ["/app/start.sh"]

# 设置镜像元数据
LABEL maintainer="坐公交也用券 <https://liumou.site>"
LABEL org.opencontainers.image.source="https://gitee.com/liumou_site/ssh-connection-detection"
LABEL org.opencontainers.image.description="SSH连接检测工具"
LABEL org.opencontainers.image.version="1.0.1"
LABEL org.opencontainers.image.licenses="MIT"